<?php

namespace app\core\middleware;

use app\core\Request;
use app\core\Response;
use app\core\util\Token;

class JwtMemberAuth
{
    /**
     * 绕过登录验证
     * @var array
     */
    private $ignore = [];

    /**
     * Token Key
     * @var string
     */
    private $tokenName = "accessToken";

    /**
     * @var Request
     */
    private $request = null;

    public function handle(Request $request, \Closure $next, $ignore = [])
    {
        $this->ignore = array_merge($this->ignore, $ignore);
        if (!in_array($request->getPerm(), $this->ignore)) {
            $this->request = $request;
            $memberInfo = $this->verifyMemberToken();
            $request->setMember($memberInfo);
        }
        return $next($request);
    }

    /**
     * @return string|null
     */
    public function getToken(): ?string
    {
        $request = $this->request;
        $tokenName = $this->tokenName ?? "token";
        return $request->header($tokenName, $request->post($tokenName, $request->get($tokenName, "")));
    }


    /**
     * 校验 Token
     * @return array|void|null
     */
    public function verifyMemberToken(): array
    {
        try {
            return Token::invoke()
                ->setBusy(false)// 占线
                ->verifyMemberToken($this->getToken());
        } catch (\Exception $e) {  //其他错误
            Response::invoke()->invalidError();
        }
    }
}